package com.pocket.insight.base.utils;

import com.pocket.insight.entity.ParamAttrOptions;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 描述：
 *
 * @author shuize
 * @create 2024/12/9
 */
public class ParamAttrUtil {

    private static final Pattern PARAM_PATTERN = Pattern.compile("\\{\\{%%.+?\\}\\}");
    private static final Pattern ATTR_PATTERN = Pattern.compile("\\{\\{\\$\\$.+?\\}\\}");
    private static final Pattern PARAM_FORMULA_PATTERN = Pattern.compile("\\{\\{%.+?\\}\\}");
    private static final Pattern ATTR_FORMULA_PATTERN = Pattern.compile("\\{\\{\\$.+?\\}\\}");


    public static boolean isStringContainsAttrOrParamInReplacementFormat(String s) {
        return (isStringContainsAttr(s) || isStringContainsParam(s));
    }

    public static boolean isStringContainsAttr(String s) {
        if (StringUtils.isBlank(s)) {
            return false;
        }
        Matcher attrMatcher = ATTR_PATTERN.matcher(s);
        return attrMatcher.find();
    }

    public static boolean isStringContainsParam(String s) {
        if (StringUtils.isBlank(s)) {
            return false;
        }
        Matcher paramMatcher = PARAM_PATTERN.matcher(s);
        return paramMatcher.find();
    }


    public static Object buildParamMultiValue(Object value, ParamAttrOptions.MultiValueConfig multiValueConfig) {
        if (value instanceof List && multiValueConfig != null && !BooleanUtils.isNotTrue(multiValueConfig.getEnable())) {
            List list = (List)value;
            String prefix = addEscapeCharacterDoubleQuotationMark(multiValueConfig.getPrefix());
            String suffix = addEscapeCharacterDoubleQuotationMark(multiValueConfig.getSuffix());
            String quote = addEscapeCharacterDoubleQuotationMark(multiValueConfig.getQuote());
            String split = addEscapeCharacterDoubleQuotationMark(multiValueConfig.getSplit());
            if (CollectionUtils.isEmpty(list)) {
                return StringUtils.isAllBlank(prefix, suffix) ? "null" : prefix + suffix;
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append(prefix);
                list.forEach((item) -> {
                    sb.append(String.format("%s%s%s%s", quote, item, quote, split));
                });
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                }

                sb.append(suffix);
                return sb.toString();
            }
        } else {
            return value;
        }
    }

    private static String addEscapeCharacterDoubleQuotationMark(String c) {
        return c != null && c.equals("\"") ? "\\\"" : c;
    }
}
